<?php

use models\Observatorio;
use models\dao\ObservatorioDAO;
class Observatorios extends CI_Controller {

	private $observatorioDAO;
	private $em;

	public function __construct() {
		parent::__construct();

		$this->em = $this->doctrine->em;
		$this->observatorioDAO = new ObservatorioDAO($this->em);
	}

	public function index() {
		echo "teste";
	}

	public function findAll() {
		$observatories = $this->observatorioDAO->findAll();

		$result['result'] = array();

		foreach($observatories as $observatory) {
			array_push($result['result'], $observatory->toArray());
		}

		echo json_encode($result);
	}

	public function save() {
		$data = (array) json_decode($_POST['data']);

		if (empty($data['id'])) {
			$obs = new models\Observatorio();
		} else {
			$obs = $this->observatorioDAO->findByPrimaryKey($data['id']);
		}

		$obs->setNome($data['nome']);

		$this->observatorioDAO->save($obs);

		$this->em->close();

		$result['data']['success'] = true;
		echo json_encode($result);
	}

	public function delete() {
		$data = (array) json_decode($_POST['data']);
		$result['data']['success'] = true;
		try {
			$obs = $this->observatorioDAO->findByPrimaryKey($data['id']);
			$this->observatorioDAO->delete($obs);
			echo json_encode($result);
		} catch (Exception $e) {
			$this->em->close();
			$result['data']['success'] = false;
			$result['data']['message'] = $e->getMessage();
			echo json_encode($result);
		}
	}
}